﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using Portal.Web.Model;
using Portal.Web.Utility;
using Portal.Exam.Bussiness;
using Portal.Exam.Model;
using Portal.Core;

namespace Portal.Exam.Render
{
    public class ImportExamQuestion
    {
        [AjaxPro.AjaxMethod]
        public static string GetHtml(
            string SiteId, 
            string FirstGroupQuestionId,
            string FirstMonthiId,
            string Type,
            string SelectLevel)
        {
            try
            {
                WebSessionUtility.CheckSessionTimeOut(); 
                
                DataTable dtGroupQuestion = GroupQuestionBll.ReadingGroupQuestion(SiteId, "");
                string SelectGroupQuestionText = "<select class=drplist id=drpSelectGroupQuestion onchange=javascript:DetectMonthi();>";
                for (int iIndex = 0; iIndex < dtGroupQuestion.Rows.Count; iIndex++)
                {
                    string GroupQuestionId = (string)dtGroupQuestion.Rows[iIndex]["GroupQuestionId"];
                    string Name = (string)dtGroupQuestion.Rows[iIndex]["Name"];
                    if (FirstGroupQuestionId.Trim().Length == 0 && iIndex == 0)
                    {
                        FirstGroupQuestionId = GroupQuestionId;
                    }
                    if (FirstGroupQuestionId.Equals(GroupQuestionId))
                    {
                        SelectGroupQuestionText += "<option selected value=\"" + GroupQuestionId + "\">" + Name + "</option>";
                    }
                    else
                    {
                        SelectGroupQuestionText += "<option value=\"" + GroupQuestionId + "\">" + Name + "</option>";
                    }
                }
                SelectGroupQuestionText += "</select>";

                DataTable dtMonthi = new MonthiBll().ReadingMonthi(SiteId, FirstGroupQuestionId, "");
                string SelectMonthiText = "<select class=drplist id=drpSelectMonthi onchange=javascript:ResetSearch();>";
                for (int iIndex = 0; iIndex < dtMonthi.Rows.Count; iIndex++)
                {
                    string MonthiId = (string)dtMonthi.Rows[iIndex]["MonthiId"];
                    string Name = (string)dtMonthi.Rows[iIndex]["Name"];
                    if (FirstMonthiId.Trim().Length == 0 && iIndex == 0)
                    {
                        FirstMonthiId = MonthiId;
                    }
                    if (FirstMonthiId.Equals(MonthiId))
                    {
                        SelectMonthiText += "<option selected value=\"" + MonthiId + "\">" + Name + "</option>";
                    }
                    else
                    {
                        SelectMonthiText += "<option value=\"" + MonthiId + "\">" + Name + "</option>";
                    }
                }
                SelectMonthiText += "</select>";

              

                string[] Types = new string[]{
                    "BestAnswer","YesNo"//,"MultiChoice"
                };
                string[] SubjectTypes = new string[]{
                    "Câu hỏi 1 phương án đúng nhất","Câu hỏi dạng đúng hoặc sai"//,"Các đáp án đúng"
                };

                string SelectTypeText = "<select class=drplist id=drpSelectType onchange=javascript:JumPageImportExamQuestion(0);>";
                for (int iIndex = 0; iIndex < Types.Length; iIndex++)
                {
                    if (Types.Length == 0 && iIndex == 0)
                    {
                        Type = Types[iIndex];
                    }
                    if (Type.ToLower().Equals(Types[iIndex].ToLower()))
                    {
                        SelectTypeText += "<option selected value=\"" + Types[iIndex] + "\">" + SubjectTypes[iIndex] +" ("+Types[iIndex]+") </option>";
                    }
                    else
                    {
                        SelectTypeText += "<option value=\"" + Types[iIndex] + "\">" + SubjectTypes[iIndex] +" ("+Types[iIndex]+")</option>";
                    }
                }
                SelectTypeText += "</select>";

                
                string SelectLevelText =
                    "<select id=drpSelectLevelImportExamQuestion class=drplist>\r\n" +
                    "   <option value=\"0\">Mức độ dễ</option>\r\n" +
                    "   <option value=\"1\">Mức độ trung bình</option>\r\n" +
                    "   <option value=\"2\">Mức độ khó</option>\r\n" +
                    "</select>\r\n";

                if (SelectLevel.Equals("1"))
                {
                    SelectLevelText =
                      "<select id=drpSelectLevelImportExamQuestion class=drplist>\r\n" +
                      "   <option value=\"0\">Mức độ dễ</option>\r\n" +
                      "   <option value=\"1\" selected>Mức độ trung bình</option>\r\n" +
                      "   <option value=\"2\">Mức độ khó</option>\r\n" +
                      "</select>\r\n";
                }
                if (SelectLevel.Equals("2"))
                {
                    SelectLevelText =
                      "<select id=drpSelectLevelImportExamQuestion class=drplist>\r\n" +
                      "   <option value=\"0\">Mức độ dễ</option>\r\n" +
                      "   <option value=\"1\">Mức độ trung bình</option>\r\n" +
                      "   <option value=\"2\" selected>Mức độ khó</option>\r\n" +
                      "</select>\r\n";
                }

                string SelectOverwriteText =
                    "<select id=drpSelectOverwrite class=drplist>\r\n" +
                    "   <option value=\"0\">Không đè nếu tồn tại</option>\r\n" +
                    "   <option value=\"1\">Ghi đè nếu tồn tại</option>\r\n" +
                    "</select>\r\n";
                string RetHtml =
                    " <div class=CssFormSaveUpdate>\r\n" +
                    "   <table>" +
                    "       <tr>" +
                    "           <td class=Col1>Nhóm câu hỏi:</td>" +
                    "           <td class=Col2>" + SelectGroupQuestionText + "</td>" +
                    "       </tr>" +
                    "       <tr>" +
                    "           <td class=Col1>Loại câu hỏi:</td>" +
                    "           <td class=Col2><div id=divMonthiContent>" + SelectMonthiText + "</div></td>" +
                    "       </tr>" +
                    "       <tr>" +
                    "           <td class=Col1>Kiểu câu hỏi:</td>" +
                    "           <td class=Col2>" + SelectTypeText + "</td>" +
                    "       </tr>" +
                    "       <tr>" +
                    "           <td class=Col1>Mức độ:</td>" +
                    "           <td class=Col2>" + SelectLevelText + "</td>" +
                    "       </tr>" +
                    "       <tr>" +
                    "           <td class=Col1>Tham số:</td>" +
                    "           <td class=Col2>" + SelectOverwriteText + "</td>" +
                    "       </tr>" +
                    "       <tr>\r\n"+
                    "           <td class=Col1>Chọn tệp:</td>\r\n"+
                    "           <td class=Col2>\r\n"+
                    "                   <input type=\"file\" name=\"fileToUpload[]\" id=\"fileToUpload\" onchange=\"fileSelected();\" /><div style=\"margin-top:10px;\"></div>\r\n" +//<input type=button class=button onclick=\"uploadFile()\" value=\"Thực hiện nhập dữ liệu từ tệp\" /><input type=button class=button onclick=\"SaveLog()\" value=\"Ghi Log import\" />
                    "                   <div id=divLinkSaveLog></div>\r\n" +
                    "                   <div id=\"fileName\"></div>\r\n" +
                    "                   <div id=\"fileSize\"></div>\r\n" +
                    "                   <div id=\"fileType\"></div>\r\n" +
                    "                   <div id=divProcessing></div>\r\n" +
                    "                   <div id=\"divImportLog\" style=\"padding:4px;border:solid 1px silver;height:200px;overflow:auto;display:none;\"></div>\r\n" +
                    "                   <input type=hidden id=txtImportFile value=\"\">\r\n" +
                    "                   <div class=CssTip style=\"color:maroon;font-size:12px;\"><i>(*) Chú ý: File phải đúng định dạng quy định theo <a href=\"ExcelTemplate/ExamStudentList.xls\">biểu mẫu</a> sau đó save as thành file text với định dạng unicode và dùng file này để import</i></div>\r\n" +
                    "           </td>\r\n"+
                    "       </tr>\r\n"+
                    "   </table>" +
                    " </div>\r\n" +
                    " <div id=divProcessing></div>";
                   
                return RetHtml;
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetMonthi(string SiteId,string FirstGroupQuestionId)
        {
            try
            {
                WebSessionUtility.CheckSessionTimeOut(); 
                DataTable dtMonthi = new MonthiBll().ReadingMonthi(SiteId, FirstGroupQuestionId, "");
                string SelectMonthiText = "<select class=drplist id=drpSelectMonthi onchange=javascript:ResetSearch();>";
                for (int iIndex = 0; iIndex < dtMonthi.Rows.Count; iIndex++)
                {
                    string MonthiId = (string)dtMonthi.Rows[iIndex]["MonthiId"];
                    string Name = (string)dtMonthi.Rows[iIndex]["Name"];
                    SelectMonthiText += "<option value=\"" + MonthiId + "\">" + Name + "</option>";
                }
                SelectMonthiText += "</select>";
                return SelectMonthiText;
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }

        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                string GroupQuestionId = (string)WebEnvironments.Request(SiteId, "GroupQuestionId");
                if (string.IsNullOrEmpty(GroupQuestionId)) GroupQuestionId = "";
                string MonThiId = (string)WebEnvironments.Request(SiteId, "MonThiId");
                if (string.IsNullOrEmpty(MonThiId)) MonThiId = "";
                string Type = (string)WebEnvironments.Request(SiteId, "Type");
                if (string.IsNullOrEmpty(Type)) Type = "";
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string IconRoot = WebConfig.GetButtonIconRoot(OSiteParam);


                string RetHtml =
                        "<script language=javascript>\r\n" +
                        " function DetectMonthi() \r\n" +
                        " { \r\n" +
                        "     SiteId='" + SiteId + "';\r\n" +
                        "     GroupQuestionId=document.getElementById(\"drpSelectGroupQuestion\").options[document.getElementById(\"drpSelectGroupQuestion\").selectedIndex].value; \r\n" +
                        "     retValue=Portal.Exam.Render.ImportExamQuestion.GetMonthi(SiteId, GroupQuestionId).value; \r\n" +
                        "     document.getElementById(\"divMonthiContent\").innerHTML=retValue; \r\n" +
                        "     document.getElementById(\"divProcessing\").innerHTML=\"\"; \r\n" +
                        "     document.getElementById(\"divResultContent\").innerHTML=\"\"; \r\n" +
                        "     document.getElementById(\"divResultInfo\").innerHTML=\"???\"; \r\n" +
                        " } \r\n" +


                        "function fileSelected() {\r\n" +
                        "    var file = document.getElementById('fileToUpload').files[0];\r\n" +
                        "    if (file) {\r\n" +
                        "        var fileSize = 0;\r\n" +
                        "        if (file.size > 1024 * 1024)\r\n" +
                        "            fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';\r\n" +
                        "        else\r\n" +
                        "            fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';\r\n" +
                        "        document.getElementById('fileName').innerHTML = 'Tên tệp: ' + file.name;\r\n" +
                        "        document.getElementById('fileSize').innerHTML = 'Kích cỡ: ' + fileSize;\r\n" +
                        "        document.getElementById('fileType').innerHTML = 'Loại tệp: ' + file.type;\r\n" +
                        "    }\r\n" +
                        "}\r\n" +

                        "function ClientExecuteImportExamQuestion() {\r\n" +
                        "    if(confirm('Bạn đã chắc chắn nhập dữ liệu từ file chưa?')==false)return;\r\n" +
                        "    var fd = new FormData();\r\n" +
                        "    fd.append(\"fileToUpload\", document.getElementById('fileToUpload').files[0]);\r\n" +
                        "    var xhr = new XMLHttpRequest();\r\n" +
                        "    xhr.upload.addEventListener(\"progress\", uploadProgress, false);\r\n" +
                        "    xhr.addEventListener(\"load\", uploadComplete, false);\r\n" +
                        "    xhr.addEventListener(\"error\", uploadFailed, false);\r\n" +
                        "    xhr.addEventListener(\"abort\", uploadCanceled, false);\r\n" +
                        "    xhr.open(\"POST\", \"UploadHandler.ashx?SiteId=" + SiteId + "\");\r\n" +
                        "    xhr.send(fd);\r\n" +
                        " }\r\n" +

                        "function uploadProgress(evt) {\r\n" +
                        "    if (evt.lengthComputable) {\r\n" +
                        "    }\r\n" +
                        "    else {\r\n" +
                        "    }\r\n" +
                        "}\r\n" +

                        "function uploadComplete(evt) {\r\n" +
                        "    if(evt.target.responseText=='')\r\n" +
                        "    {\r\n" +
                        "       alert('Chưa chọn file để import!');\r\n" +
                        "       return;\r\n" +
                        "    }\r\n" +
                        "    /* This event is raised when the server send back a response */\r\n" +
                        "    document.getElementById('txtImportFile').value=evt.target.responseText;\r\n" +
                        "    //doan nay chay upload vao day...\r\n" +
                        "    ProcessImportFile()\r\n" +
                        "}\r\n" +

                        "function uploadFailed(evt) {\r\n" +
                        "    alert(\"Lỗi khi tải tệp dữ liệu lên máy chủ.\");\r\n" +
                        "}\r\n" +

                        "function uploadCanceled(evt) {\r\n" +
                        "    alert(\"Người dùng hủy bỏ tải lên máy chủ hoặc mất kết nối với máy chủ.\");\r\n" +
                        "}\r\n" +


                        "function ProcessImportFile()\r\n" +
                        "{\r\n" +
                        "    SiteId='" + SiteId + "';\r\n" +
                        "    ImportFile=document.getElementById('txtImportFile').value;\r\n" +
                        "    if(ImportFile=='')\r\n" +
                        "    {\r\n" +
                        "       alert('Chưa có file để nhập liệu!');\r\n" +
                        "       return;\r\n" +
                        "    }\r\n" +
                        "    AjaxOut = Portal.Exam.Render.ImportExamQuestion.ServerSideReadMaxLine(SiteId, ImportFile).value;\r\n" +
                        "    MaxLine=AjaxOut.RetNumber;\r\n" +
                        "    if(MaxLine<=1)\r\n" +
                        "    {\r\n" +
                        "       alert('Không có dữ liệu để import!');\r\n" +
                        "       return;\r\n" +
                        "    }\r\n" +
                        "    StartLine=1;\r\n" +
                        "    document.getElementById('divImportLog').innerHTML='';\r\n" +
                        "    document.getElementById('divImportLog').style.display='block';\r\n" +
                        "    setTimeout('ImportData()',30);\r\n" +
                        "}\r\n" +

                        "function ImportData()\r\n" +
                        "{\r\n" +
                        "    if(StartLine==MaxLine)\r\n" +
                        "    {\r\n" +
                        "       StartLine=1;\r\n" +
                        "       MaxLine=0;\r\n" +
                        "       ProcessBarText = Portal.Exam.Render.ImportExamQuestion.ServerSideGetProcessBar(SiteId, MaxLine, MaxLine).value;\r\n" +
                        "       document.getElementById('divProcessing').innerHTML='';\r\n" +
                        "    }\r\n" +
                        "    else\r\n" +
                        "    {\r\n" +
                        "       ProcessBarText = Portal.Exam.Render.ImportExamQuestion.ServerSideGetProcessBar(SiteId, StartLine, MaxLine).value;\r\n" +
                        "       document.getElementById('divProcessing').innerHTML=ProcessBarText;\r\n" +
                        "       ImportFile=document.getElementById('txtImportFile').value;\r\n" +
                        "       MonthiId=document.getElementById('drpSelectMonthi').value;\r\n"+
                        "       SelectType=document.getElementById('drpSelectType').value;\r\n" +
                        "       Level=document.getElementById('drpSelectLevelImportExamQuestion').value;\r\n" +
                        "       Overwrite=parseInt(document.getElementById('drpSelectOverwrite').value);\r\n" +
                        "       AjaxOut = Portal.Exam.Render.ImportExamQuestion.ServerSideProcessLine(SiteId, MonthiId, SelectType, Level , ImportFile, StartLine, Overwrite).value;\r\n" +
                        "       ImportLog=document.getElementById('divImportLog').innerHTML;\r\n" +
                        "       if(AjaxOut.Error)\r\n" +
                        "       {\r\n" +
                        "           document.getElementById('divImportLog').innerHTML=AjaxOut.InfoMessage+'<br>'+ImportLog;\r\n" +
                        "       }\r\n" +
                        "       StartLine=StartLine+1;\r\n" +
                        "       setTimeout('ImportData()',30);\r\n" +
                        "    }\r\n" +
                        "}\r\n" +


                        "</script>\r\n" +
                        " <div class=DatabaseFunction>\r\n" +
                        "        <ul>\r\n" +
                        "            <li onclick=\"javascript:ClientExecuteImportExamQuestion();\"><img class=image src=\"" + IconRoot + "/Execute.png\"><div>Thực hiện nhập liệu</div></li>\r\n" +
                        "            <li onclick=\"javascript:window.open('../../folder.aspx?folder=exam','_self');\"><img class=image src=\"" + IconRoot + "/back.png\"><div>Quay lại</div></li>\r\n" +
                        "        </ul>\r\n" +
                        "  </div>\r\n" +
                        "<h3>Nạp ngân hàng câu hỏi từ tệp xml</h3>\r\n" +
                        "<div id=divImportExamQuestionMain class=cssDivImportExamQuestion>" + GetHtml(SiteId, GroupQuestionId, MonThiId, Type, "0") + "</div>";
                        
                OAjaxOut.HtmlContent = RetHtml;
            }
            catch (Exception ex) 
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage=ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            return OAjaxOut;
        }


        [AjaxPro.AjaxMethod]
        public static AjaxOut ServerSideReadMaxLine(string SiteId, string ImportFile)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                DataSet ds = new DataSet();
                ds.ReadXml(ImportFile);
                OAjaxOut.RetNumber = ds.Tables["Question"].Rows.Count;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
            }
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod]
        public static string ServerSideGetProcessBar(string SiteId, int ProcessLine, int MaxLine)
        {
            int MaxW = 700;
            decimal W = 0;
            decimal Percent = 0;
            if (MaxLine > 0)
            {
                W = (decimal)MaxW * (decimal)ProcessLine / (decimal)MaxLine;
                Percent = ((decimal)ProcessLine / (decimal)MaxLine) * 100;
            }
            if (Percent < 1) Percent = 1;
            if (Percent > 100) Percent = 100;
            string HtmlProgressBar = "<div style=\"width:" + MaxW + "px;padding:10px; background-color:silver;border:solid 1px black;height:55px;margin-top:10px;margin-bottom:10px;\">\r\n" +
                                     "   <div style=\"padding:4px;\">Xử lý dòng " + (ProcessLine + 1) + "/" + MaxLine + "</div>\r\n" +
                                     "   <div style='border:solid 1px black;padding:4px;background-color:blue;color:white;width:" + W.ToString("###0") + "px'>" + Percent.ToString("#,##0") + "% </div>\r\n" +
                                     "</div>\r\n";

            return HtmlProgressBar;
        }


        [AjaxPro.AjaxMethod]
        public static AjaxOut ServerSideProcessLine(
            string SiteId,
            string MonThiId,
            string QuestionType,
            string LevelImport,
            string ImportFile,
            int    ProcessLine,
            int    Overwrite)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            OAjaxOut.InfoMessage = "";
            QuestionCls OQuestion = new QuestionCls();
            try
            {
                DataSet ds = new DataSet();
                ds.ReadXml(ImportFile);
                DataTable dtQuestion = ds.Tables["Question"];
                if (dtQuestion == null)
                {
                    return OAjaxOut;
                }
                if (dtQuestion.Rows.Count == 0)
                {
                    return OAjaxOut;
                }
                if (ProcessLine == dtQuestion.Rows.Count)
                {
                    return OAjaxOut;
                }
                
                DataTable dtAnswer=ds.Tables["Answer"];
                string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
                string QuestionId=(string)dtQuestion.Rows[ProcessLine]["Id"];
                DataView dvAnswer=new DataView(dtAnswer,"QuestionId='"+QuestionId+"'","",DataViewRowState.CurrentRows);
                
                OQuestion.QuestionId=QuestionId;
                OQuestion.Title=(string)dtQuestion.Rows[ProcessLine]["Subject"];
                OQuestion.Type=QuestionType;
                OQuestion.Level=int.Parse(LevelImport);
                OQuestion.Answers=new System.Collections.ObjectModel.Collection<AnswerCls>{};
                for (int iIndexAnswer = 0; iIndexAnswer < dvAnswer.Count; iIndexAnswer++)
                {
                    AnswerCls OAnswer = new AnswerCls();
                    OAnswer.AnswerId = (string)dvAnswer[iIndexAnswer]["AnswerId"];
                    OAnswer.AnswerTextFirst = (string)dvAnswer[iIndexAnswer]["AnswerText"];
                    bool Correct = bool.Parse(dvAnswer[iIndexAnswer]["IsAnswer"].ToString());
                    if (Correct)
                    {
                        OQuestion.CorrectOrder = iIndexAnswer;// ?1:0;
                    }
                    OAnswer.CorrectOrder = Correct ? 1 : 0;
                    OAnswer.IndexOrder = iIndexAnswer + 1;
                    if (string.IsNullOrEmpty(OAnswer.AnswerTextFirst) && string.IsNullOrEmpty(OAnswer.AnswerTextLast))
                    {
                        //trang khong lam gi ca
                    }
                    else
                    {
                        OQuestion.Answers.Add(OAnswer);
                    }
                }
                new QuestionBll().AddQuestion(null, SiteId, MonThiId, QuestionType, int.Parse(LevelImport), OQuestion, Overwrite);
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                string ErrorMsg = ex.Message.ToString();
                if (ErrorMsg.IndexOf("Violation of PRIMARY KEY") != -1)
                {
                    ErrorMsg = "Đã có câu hỏi '"+OQuestion.Title+"' trong cơ sở dữ liệu";
                }
                OAjaxOut.InfoMessage = "Lỗi xử lý dòng " + (ProcessLine + 1) + " => " + ErrorMsg;
            }
            return OAjaxOut;
        }

    }
}
